import { useMemo } from 'react';
import style from './style.module.scss'
import { useCompareStore } from '@/stores/compareStore'
import { RocketOutlined } from '@ant-design/icons';
import { Card, Carousel } from 'antd';
import Meta from 'antd/es/card/Meta';
import TopList from '@/components/lists/topList/Toplist';
import Comment from '@/components/comments/Comment';
import { useEffect, useState } from 'react';
import http from '@/api/axios';
import type { Food } from '@/Interface/BrandInterface';


const Left = () => {
  const compare = useCompareStore((state) => state.compare);

  const [newFoodData, setNewFoodData] = useState<Food[] | null>(null)
  const [packageData, setPackageData] = useState<Food[] | null>(null)

  useEffect(() => {
    const getData = async () => {
      try {
        const [newFoodRes, packageRes] = await Promise.all([
          http.get('/api/newfood'),
          http.get('/api/package')
        ]);
        setNewFoodData(newFoodRes.data.data);
        setPackageData(packageRes.data.data);
      } catch (error) {
        console.error('初始化数据失败:', error);
      }
    }
    getData()
  }, [newFoodData, packageData])

  const carouselContent = useMemo(() => (
    <div className={style.carousel}>
      <div className={style.child}>
        <h3>新品上市</h3>
        <Carousel autoplay>
          {newFoodData?.map((item) =>
            <Card cover={
              <img
                alt={item.name || "新品图片"}
                src={item.src}
                loading="eager"    // 立即加载
                decoding="async"   // 异步解码
                fetchPriority="high"   // 优先级
              />
            }
            >
              <Meta title={item.name} />
            </Card>
          )}
        </Carousel>
      </div>
      <div className={style.child}>
        <h3>热销套餐</h3>
        <Carousel autoplay>
          {packageData?.map((item) =>
            <Card
              cover={
                <img
                  alt={item.name || "热销图片"}
                  src={item.src}
                  loading="eager"    // 立即加载
                  decoding="async"   // 异步解码
                  fetchPriority="high"   // 优先级
                />
              }
            >
              <Meta title={item.name} />
            </Card>
          )}
        </Carousel>
      </div>
    </div>
  ), [newFoodData, packageData]); // 仅数据变化时重新渲染

  return (
    <div className={`${style.size} ${compare && style.hide} `}>
      <div className={style.inner}>
        <div className={style.topList}>
          <div className={style.head}>
            <RocketOutlined /> 龙虎榜 <RocketOutlined />
          </div>
          <TopList />
        </div>
        {carouselContent}
        <div className={style.comments}>
          <Comment />
        </div>
      </div>
    </div >
  )
}


export default Left;